package com.gqr.threadcoreknowledge.stopthreads;

/*
* 线程在每次迭代后都阻塞
* 如果在执行过程中，每次循环都会调用sleep活wait等方法，
* 那么不需要每次迭代都检查是否已中断
*
* 是否还需要!Thread.currentThread().isInterrupted() 这个判断
*
* */
public class RightWayStopThreadWithSleepEveryLoop {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (num <= 10000 ) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    /*
                    * 每次循环都会执行sleep 每次循环过程又不会长 大部分时间都是消耗在Thread.sleep中
                    * 在休眠中收到interrupt 就会抛出异常 打出异常堆栈
                    * */
                    num++;
                    Thread.sleep(10);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }
}
